package com.hq.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hq.bean.City;
import com.hq.bean.User;
import com.hq.service.UserService;
import com.hq.util.FileUploadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
public class UserController {
    @Resource
    private UserService service;
    
    @RequestMapping("login.do")
    public String login(String name,String password){
        if (name!=null&&password!=null) {
            int login = service.login(name, password);
            if (login > 0) {
                return "redirect:list.do";
            }
        }
        return "fail";
    }

    @RequestMapping("list.do")
    public String list(@RequestParam(value = "pages",defaultValue = "1")Integer pages, String name, String start, String end, Integer sheng, Integer shi, Integer xian, Model model){
        PageHelper.startPage(pages,3);
        HashMap map = new HashMap();
        map.put("name",name);
        map.put("start",start);
        map.put("end",end);
        map.put("sheng",sheng);
        map.put("shi",shi);
        map.put("xian",xian);
        List<User> list = service.list(map);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        model.addAttribute("map",map);
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }

    @RequestMapping("city.do")
    @ResponseBody
    public Object city(Integer pid){
        List<City> city = service.city(pid);
        return city;
    }

    @RequestMapping("toadd.do")
    public String toadd(){
        return "add";
    }

    @RequestMapping("add.do")
    @ResponseBody
    public Object add(User user, MultipartFile photo, HttpSession session){
        String upload = FileUploadUtil.load(session, photo, "upload");
        user.setPic(upload);
        int add = service.add(user);
        return add;
    }

    @RequestMapping("getById.do")
    @ResponseBody
    public Object getById(Integer id){
        User byId = service.getById(id);
        return byId;
    }

    @RequestMapping("toupd.do")
    public String toupd(){
        return "upd";
    }

    @RequestMapping("upd.do")
    @ResponseBody
    public Object upd(User user){
        int add = service.upd(user);
        return add;
    }
}
